package org.kumas.sgrpc.rpc.protocol.sgrpc;

import org.kumas.sgrpc.common.URL;
import org.kumas.sgrpc.common.extension.ExtensionLoader;
import org.kumas.sgrpc.common.serialize.Serialization;
import org.kumas.sgrpc.remoting.transport.CodecSupport;
import org.kumas.sgrpc.rpc.AppResponse;
import org.kumas.sgrpc.rpc.Invocation;

import static org.kumas.sgrpc.rpc.Constants.INVOCATION_KEY;
import static org.kumas.sgrpc.rpc.Constants.SERIALIZATION_ID_KEY;

public class SgrpcCodecSupport {

    public static Serialization getRequestSerialization(URL url, Invocation invocation) {
        Object serializationType_obj = invocation.get(SERIALIZATION_ID_KEY);
        if (serializationType_obj != null) {
            return CodecSupport.getSerializationById((byte) serializationType_obj);
        }
        return ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(
                url.getParameter(org.kumas.sgrpc.remoting.Constants.SERIALIZATION_KEY, Constants.DEFAULT_REMOTING_SERIALIZATION));
    }

    public static Serialization getResponseSerialization(URL url, AppResponse appResponse) {
        Object invocation_obj = appResponse.getAttribute(INVOCATION_KEY);
        if (invocation_obj != null) {
            Invocation invocation = (Invocation) invocation_obj;
            Object serializationType_obj = invocation.get(SERIALIZATION_ID_KEY);
            if (serializationType_obj != null) {
                return CodecSupport.getSerializationById((byte) serializationType_obj);
            }
        }
        return ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(
                url.getParameter(Constants.SERIALIZATION_KEY, Constants.DEFAULT_REMOTING_SERIALIZATION));
    }
}